<?php

namespace Index\Controller;
use Think\Controller;
use Org\Util\Wechat;

class ApiController extends Controller{
	
	public $config = array(
		'appid'         =>'wx7197628dc9966e3d',
		'token'         =>'zhijin101',
		'encodingaeskey'=>'CvECAzjZteRdhjTinszJesrxkyhXKGfstSSGgEKahSe',
		'appsecret'     =>'2df3acd8ec9b083b374fedf18fa723e5',
		'debug'         =>false,
	);
	
	public function index(){
		$wx = new Wechat($this->config);
		$wx->valid();
		$wx->text('END')->reply(); 
		
		exit();
		$wx->checkAuth(); 
	
	
		//获取事件类型
		$type = $wx->getRev()->getRevType();
		switch ($type) {
			case Wechat::MSGTYPE_TEXT:	//文字
				$this->onTextEvent();
				break;
			case Wechat::MSGTYPE_IMAGE:	//图片
				$this->onImageEvent();
				break;
			case Wechat::MSGTYPE_LOCATION:	//位置
				$this->onLocationEvent();
				break;
			case Wechat::MSGTYPE_LINK:	//链接
				$this->onLinkEvent();
				break;
			case Wechat::MSGTYPE_EVENT:  //事件
				$this->onEventEvent();
				break;
			case Wechat::MSGTYPE_MUSIC:	//音乐 
				$this->onMusicEvent();
				break;
			case Wechat::MSGTYPE_NEWS:	//新闻
				$this->onNewsEvent();
				break;
			case Wechat::MSGTYPE_VOICE:	//声音
				$this->onVoiceEvent();
				break;
			case Wechat::MSGTYPE_VIDEO:	//视频
				$this->onVideoEvent();
				break;
			default :
				$wx->text('END')->reply();
				break;
		}
	}
	
	public function onTextEvent(){
		
	}
	public function onImageEvent(){
		
	}
	public function onLocationEvent(){
		
	}
	public function onLinkEvent(){
		
	}
	public function onEventEvent(){
		
	}
	public function onMusicEvent(){
		
	}
	public function onNewsEvent(){
		
	}
	public function onVoiceEvent(){
		
	}
	public function onVideoEvent(){
		
	}
	
	
	public function test(){
		
		$wx = new Wechat($this->config);
		//$wx->valid(); 
		$wx->checkAuth(); 
		P($wx);
	}
	
	/**
	 * 设置缓存，按需重载
	 * @param string $cachename
	 * @param mixed $value
	 * @param int $expired
	 * @return boolean
	 */
	protected function setCache($cachename,$value,$expired){
		//TODO: set cache implementation
		//使用数据库缓存Token
		$data = array(
			'cachename' => $cachename,
			'value' => $value,
			'expired' => $expired+time(),
		);
		
		M('Token')->data($data)->add();
		
		/*  使用文件缓存
		$obj = json_encode(array('value'=>$value,'expired'=>time()+7000));
		file_put_contents($cachename,$obj);
		*/
		return false;
	}

	/**
	 * 获取缓存，按需重载
	 * @param string $cachename
	 * @return mixed
	 */
	protected function getCache($cachename){
		return false;
		//TODO: set cache implementation
		//使用数据库缓存Token
		$data = array(
			'cachename' => $cachename
		);
		
		$obj = M('Token')->where($data)->limit(1)->order('create_time desc')->find();
		if($obj['expired']>time()){
			return $obj['value'];
		}else{ 
			return false;
		} 
		
		/*  使用文件缓存
		if(file_exists($cachename)){ 
			$obj = json_decode(file_get_contents($cachename),true); 
			if(intval($obj['expired'])>time()){ 
				return $obj['value'];
			}else{ 
				return false;
			}
		}else{
			return false;
		}
		*/
		return false;
	}
	
	
}